package esi.t2no1.web.invoice;

import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import esi.t2no1.dao.meterdata.MeterDataDAO;
import esi.t2no1.dao.meterdata.MeterDataDTO;

/**
 * Controller that handles invoice related views
 * 
 * @author Taavi Pauskar
 *
 */
@Controller
@RequestMapping(value = "/invoice")
public class InvoiceController {
	private MeterDataDAO meterDataDAO;

	public Invoice generateInvoice(Long meterDataId) {
		MeterDataDTO meterdata = meterDataDAO.getMeterDataById(meterDataId);
		Date meterReadTime = meterdata.getReadTime();
		String meteringReadingId = meterdata.getId().toString();
		String facilityId = meterdata.getFacilityId();
		Long amountDue = (long) (Math.random()*1000);
		Calendar cal = Calendar.getInstance();
		cal.setTime(meterReadTime);
		cal.add(Calendar.DATE, 30);
		Date invoiceDueDate = cal.getTime();
		return new Invoice(meterReadTime, amountDue, invoiceDueDate, meteringReadingId, facilityId);		
	}
	
    @RequestMapping(value="{id}", method=RequestMethod.GET)
    public String getView(@PathVariable Long id, Model model) {
        Invoice invoice = generateInvoice(id);
        model.addAttribute(invoice);
        return "invoice/view";
    }
    
	@Autowired
	public void setMeterDataDAO(MeterDataDAO meterDataDAO) {
		this.meterDataDAO = meterDataDAO;
	}
}
